package jdbc.db;


import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DBUtils {

    private static Properties dbconfig;
    private static String url;
    private static String username;
    private static String password;
    private static String driverClass;

    private static ComboPooledDataSource dataSource;

    static {
        dbconfig = new Properties();
        try {
            dbconfig.load(DBUtils.class.getClassLoader().getResourceAsStream("db.properties"));
            url = dbconfig.getProperty("db.mysql.url");
            username = dbconfig.getProperty("db.mysql.username");
            password = dbconfig.getProperty("db.mysql.password");
            driverClass = dbconfig.getProperty("db.mysql.driver");

            dataSource = new ComboPooledDataSource();
            dataSource.setJdbcUrl(url);
            dataSource.setDriverClass(driverClass);
            dataSource.setUser(username);
            dataSource.setPassword(password);
        } catch (IOException | PropertyVetoException e) {
            e.printStackTrace();
        }
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }

    public static Connection getConnectionByC3P0() throws SQLException {
        return dataSource.getConnection();
    }


    public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        if (connection != null) {
            connection.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (resultSet != null) {
            resultSet.close();
        }
    }


}
